package com.donar.concurrent.lock;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * TicketLock 每次都要查询一下 serviceNum 影响性能 但是他是公平锁保证了顺序访问 （必须要到主内存读取，并阻止其他cpu修改）
 */
public class TicketLock {
    private AtomicInteger serviceNum = new AtomicInteger();
    private AtomicInteger ticketNum = new AtomicInteger();
    ThreadLocal<Integer> LOCAL = new ThreadLocal<Integer>();
    public void lock(){
        int myticketNum = ticketNum.getAndIncrement();
        LOCAL.set(myticketNum);
        while (myticketNum !=serviceNum.get()){}
    }
    public void unlock(){
        int myticketNum = LOCAL.get();
        serviceNum.compareAndSet(myticketNum,myticketNum+1);
    }
}
